/**
 * 用户地址接口
 */
const express = require('express')
const address = express.Router()

// 引入数据库
const db = require('../utils/db')
// 引入加密模块
const crypo = require('../utils/crypo')

/* 获取用户的全部收货地址 */
address.get('/addresslist', (req, res) => {
   const { username } = req.query
   const sql = `SELECT * FROM address WHERE username='${username}'`
   db.query(sql, (err, results) => {
      res.json({ addressList: results, msg: 'ok'})
   })
})

/* 新增一条用户的收货地址 */
address.post('/insertaddress', (req, res) => {
   const { realname, phone, address, username } = req.body
   const sql = `INSERT INTO address(realname,phone,address,username) VALUES('${realname}','${phone}','${address}','${username}')`
   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) res.json({ msg: 'ok', insertId: results.insertId })
      else res.json({ msg: 'failed' })
   })
})

/* 更新一条用户的收货地址 */
address.post('/updateaddress', (req, res) => {
   const { realname, phone, address, username, id } = req.body
   const sql = `UPDATE address SET realname='${realname}',phone='${phone}',address='${address}',username='${username}' WHERE id=${id}`
   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) res.json({ msg: 'ok' })
      else res.json({ msg: 'failed' })
   })
})

/* 删除一条用户的收货地址 */
address.post('/deladdress', (req, res) => {
   const { address_id } = req.body
   const sql = `DELETE FROM address WHERE id=${address_id}`
   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) res.json({ msg: 'ok' })
      else res.json({ msg: 'failed' })
   })
})

module.exports = address